package com.synnex.mobile.servier.web.utils;

import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;

import javapns.notification.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: kerryf
 * Date: 13-7-17
 * To change this template use File | Settings | File Templates.
 */
public class IOSPushMsgUtil {

    /**

     * apple's push notification
     * @param tokens   token get by ios device
     * @param fileName this is a auth file(p12 file) path when send message to APNS need this path
     * @param password  p12 file's password
     * @param message this is a Content need to push to client
     * @param count the number on the app pic lower right corner
//     * @param sendCount single send or multiple send(true：single send false：multiple send)
     * @param isProd  true: not test; false: test
     */

    public List<String> sendPush(List<String> tokens,String fileName, String password, String message,Integer count,boolean isProd) {

        List<String> failedTokens = new ArrayList<String>();
        String path=this.getClass().getResource("/").getPath().substring(0,this.getClass().getResource("/").getPath().indexOf("/classes"));
        path = path.replaceAll("%20"," ");
         path+= File.separator+fileName;
        System.out.println(path);

        PushNotificationManager pushManager = new PushNotificationManager();
        try {
            PushNotificationPayload payLoad =  PushNotificationPayload.fromJSON(message);
//            PushNotificationPayload payLoad =  new PushNotificationPayload();
            payLoad.addSound("default"); // sound
            if(count!=null){
                payLoad.addBadge(count); // iphone app message count total
            }
//            payLoad.addAlert(message);

            AppleNotificationServer APNSServer = new AppleNotificationServerBasicImpl(path, password, isProd);

            System.out.println("isProd:"+isProd+"; serverHost :" + APNSServer.getNotificationServerHost()+"; serverPort :"+APNSServer.getNotificationServerPort());
            pushManager.initializeConnection(APNSServer);



            //this list used save notification which had sended to APNS
            List<PushedNotification> notifications = new ArrayList<PushedNotification>();

            System.out.println("--------------------------messge-------"+payLoad.toString());
            // send notification message
            if (tokens!=null && !tokens.isEmpty()) {
                if (tokens.size()==1) {
                    System.out.println("--------------------------IOS send message single-------");
                    System.out.println("---token: "+tokens.get(0));
                    Device device = new BasicDevice();
                    device.setToken(tokens.get(0));
                    PushedNotification notification = pushManager.sendNotification(device, payLoad, true);
                    notifications.add(notification);
                } else {
                    System.out.println("--------------------------apple message more user-------");
                    List<Device> devices = new ArrayList<Device>();
                    for (String token : tokens) {
                        devices.add(new BasicDevice(token));
                    }
                    notifications = pushManager.sendNotifications(payLoad, devices);
                }
                List<PushedNotification> failedNotifications = PushedNotification.findFailedNotifications(notifications);
                List<PushedNotification> successfulNotifications = PushedNotification.findSuccessfulNotifications(notifications);

                int failed = failedNotifications.size();
                int successful = successfulNotifications.size();

                if (successful > 0 && failed == 0) {
                    System.out.println("-----All notifications pushed success (" + successfulNotifications.size() + "):");
                } else if (successful == 0 && failed > 0) {
                    System.out.println("-----All notifications fail (" + failedNotifications.size() + "):");
                    for(PushedNotification fail: failedNotifications){

                        failedTokens.add(fail.getDevice().getToken());
                        System.out.println("-----device token : "+fail.getDevice().getToken());
                        System.out.println("-----reason: "+fail.getException());
                    }

                } else if (successful == 0 && failed == 0) {
                    System.out.println("No notifications could be sent, probably because of a critical error");
                } else {
                    System.out.println("------Some notifications fail (" + failedNotifications.size() + "):");
                    System.out.println("------Others success (" + successfulNotifications.size() + "):");

                    for(PushedNotification fail: failedNotifications){
                        failedTokens.add(fail.getDevice().getToken());
                        System.out.println("-----device : "+fail.getDevice());
                        System.out.println("-----reason: "+fail.getException());
                    }
                }
            } else {
                System.out.println("-----------No tokens exist");
            }
            pushManager.stopConnection();
        } catch (Exception e) {
            pushManager.stopConnection();
            e.printStackTrace(System.out);
        }finally {
            return failedTokens;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws CommunicationException, KeystoreException {
        IOSPushMsgUtil pushMsgUtil=new IOSPushMsgUtil();
        List<String> tokens=new ArrayList<String>();
        tokens.add("a31ea80958b3a46bab640e4233a76740294fd3fb422b7c2fdc1f5834a1509f1a");
        String path= "promocentralPNSCer_iPhone.p12";
        String password="synnex";
        String message="{'aps':{'alert':'iphone send message'},'pid':'p123,p234,p456'}";
        boolean isTest=false;
        pushMsgUtil.sendPush(tokens, path, password, message, null, isTest);
    }
}
